package com.sunrise.comunicacao.repositorio;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.sunrise.comunicacao.repositorio.iface.BlackListDao;
import com.sunrise.generico.acesso.DaoService;
import com.sunrise.generico.entidade.BlackList;
import com.sunrise.generico.visao.Filtro;

@Repository
public class BlackListDaoImpl extends DaoService<BlackList> implements BlackListDao {

	public List<BlackList> listarOrdenado() {
		List<BlackList> list = listar(BlackList.class);
		Collections.sort(list, new Comparator<BlackList>() {

			@Override
			public int compare(BlackList o1, BlackList o2) {
				return o1.getNome().compareTo(o2.getNome());
			}
		});
		return list;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<BlackList> listarAtivos() {
		Criteria crit = getSession().createCriteria(BlackList.class);
		crit.add(Restrictions.eq("ativo", Boolean.TRUE));
		return crit.list();
	}

	public List<BlackList> search(BlackList ex) {
		List<BlackList> list =  searchByExample(BlackList.class, ex);
		Collections.sort(list, new Comparator<BlackList>() {

			@Override
			public int compare(BlackList o1, BlackList o2) {
				return o1.getNome().compareTo(o2.getNome());
			}
		});
		return list;
	}

	public BlackList getById(Long id) {
		return getById(id, BlackList.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BlackList> listarPorNome(String nome) {
		Criteria crit = getSession().createCriteria(BlackList.class);
		crit.add(Restrictions.ilike("nome", nome, MatchMode.ANYWHERE));
		return crit.list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<BlackList> buscarPorFiltros(Filtro comunicacaoSMS) {
		Criteria crit = getSession().createCriteria(BlackList.class);
		if (comunicacaoSMS.getNome() != null) {
			crit.add(Restrictions.ilike("nome", comunicacaoSMS.getNome(),
					MatchMode.ANYWHERE));
		}

		if (comunicacaoSMS.getAtivo() != null) {
			crit.add(Restrictions.eq("ativo", comunicacaoSMS.getAtivo().getCodigo()));
		}
		
		crit.addOrder(Order.asc("nome"));
		return crit.list();
	}
	
	@Override
	public BlackList buscarPorNome(String nome) {
		Criteria crit = getSession().createCriteria(BlackList.class);
		crit.add(Restrictions.eq("nome", nome).ignoreCase());
		return (BlackList) crit.uniqueResult();
	}

	@Override
	public BlackList buscarPorCelular(String celular) {
		Criteria crit = getSession().createCriteria(BlackList.class);
		crit.add(Restrictions.eq("celular", celular));
		return (BlackList) crit.uniqueResult();
	}

}
